﻿using System;
using System.Collections.Generic;
using System.IO;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Generic;
using innovations.ml.core.models;
using System.Linq;

namespace innovations.ml.data
{
    public class CSVWeightsLoader
    {
        public CSVWeightsLoader(string[] paths)
        {
            Paths = paths;
        }

        public void Load(int numberOfRecords = -1)
        {
            ThetaList = new List<Matrix<double>>();
            FilesLines = new List<string[]>();
            if (Paths == null || Paths.Length == 0)
                throw new ArgumentNullException("Paths property must not be null.");
            for (int i = 0; i < Paths.Length; i++)
            {
                if (string.IsNullOrEmpty(Paths[i]))
                    throw new ArgumentNullException("Paths property must not be empty.");
                FilesLines.Add(File.ReadAllLines(Paths[i]));
            }

            int count = 0;
            Matrix<double> matrix = null;
            ThetaUnRolled = null;
            foreach (var item in FilesLines)
            {
                int columnCount = item[0].Split(',').Length;
                if (numberOfRecords == -1)
                    numberOfRecords = item.Length;
                matrix = new DenseMatrix(numberOfRecords, columnCount);
                for (int i = 0; i < item.Length; i++)
                {
                    for (int j = 0; j < numberOfRecords; j++)
                    {
                        string[] lineString = item[j].Split(',');
                        double[] lineDouble = new double[lineString.Length];
                        for (int k = 0; k < columnCount; k++)
                        {
                            lineDouble[k] = Convert.ToDouble(lineString[k]);
                        }
                        matrix.SetRow(j, lineDouble);
                    }
                }
                if (count == 0)
                    ThetaUnRolled = new DenseVector(matrix.ToColumnWiseArray());
                else
                    ThetaUnRolled = new DenseVector(matrix.ToColumnWiseArray().Concat(ThetaUnRolled).ToArray());
                ThetaList.Add(matrix);
                count++;
                numberOfRecords = -1;
            }
        }
        public List<string[]> FilesLines { get; set; }
        public string[] Paths { get; set; }
        public DenseVector ThetaUnRolled { get; set; }
        public List<Matrix<double>> ThetaList { get; set; }
    }
}
